#include <stdio.h>
#include <pthread.h>
#include <stdint.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>

#define NIT_SHORT_NAMES
#include <nit/socket.h>

#include "tp-bind.h"

int
display(Nit_joint *in)
{
	char *buf = malloc(256);
	int32_t size = 256;

	if (!buf)
		return 0;

	while (1) {
		int32_t msg_size;
		int val;

		switch (val = joint_read(in, &buf, &size, &msg_size, 1)) {
		case NIT_JOIN_NONE:
			break;
		case NIT_JOIN_CLOSED:
			free(buf);
			return 1;
		case NIT_JOIN_ERROR:
			free(buf);
			return 0;
		case NIT_JOIN_OK:
			buf[msg_size] = '\0';
			printf("%s", buf);
			fflush(stdout);
			break;
		}
	}
}

int
blu_tp_bind(const char *name)
{
	int val;
	Nit_joint *jnt = joint_connect(name);

	if (!jnt)
		return 0;

	val = display(jnt);
	printf("\n");
	joint_free(jnt);
	return val;
}
